﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace INSAForManagers.Views
{
    public partial class FormCandidateList : Form
    {
        //부모 폼
        private FormACard parentForm;

        //직위
        private int jobLevel;

        //테이블
        private DataTable tblCandidates = new DataTable();

        //열
        private DataColumn colCandidates;

        //현재 선택 행
        private int selectedRowIndex = -1;
        

        public FormCandidateList(FormACard parent, int jobLevel)
        {
            //부모 폼
            this.parentForm = parent;

            //대상자 직위
            this.jobLevel = jobLevel;

            InitializeComponent();
        }

        private void FormCandidateList_Load(object sender, EventArgs e)
        {
            try
            {

                //DataGridView 열 추가
                makeColumn();

                //DataGridView 행 추가
                makeRow(getCadidates(this.jobLevel));

                //행 추가/삭제 링크 보기 여부(교감인 경우에만 보이기)
                panButton.Visible = jobLevel == 1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace,"오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// void addRow()
        /// 행을 추가한다.
        /// </summary>
        private void addRow()
        {
            //행 추가
            DataRow row = tblCandidates.NewRow();
            row[0] = dgvCandidates.Rows.Count + 1;
            tblCandidates.Rows.Add(row);

            //DataGridView 설정 변경            
            dgvCandidates.Rows[dgvCandidates.Rows.Count - 1].ReadOnly = false;
            dgvCandidates.EditMode = DataGridViewEditMode.EditOnEnter;

            DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
            cell.Items.AddRange("남", "여");

            dgvCandidates.Rows[dgvCandidates.Rows.Count - 1].Cells[3] = cell;
            

        }

        /// <summary>
        /// void delRow()
        /// 선택한 행을 삭제한다.
        /// </summary>
        private void delRow()
        {

            if (selectedRowIndex == -1) return;
            
            if (selectedRowIndex == dgvCandidates.Rows.Count - 1 || dgvCandidates.Rows[selectedRowIndex].Cells[1].Value == null)
            {
                dgvCandidates.Rows.RemoveAt(selectedRowIndex);
            }
            else
            {
                DialogResult result = MessageBox.Show("대상자를 삭제하시면 입력하신 정보가 모두 삭제됩니다.\n\n그래도 삭제하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    if (delAllInfo((string)dgvCandidates.Rows[selectedRowIndex].Cells[1].Value))
                    {
                        dgvCandidates.Rows.RemoveAt(selectedRowIndex);
                        selectedRowIndex = -1;
                        MessageBox.Show("삭제하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        /// <summary>
        /// bool dellAllInfo(string pcode)
        /// 개인번호의 대상자의 승진후보자명부 작성 관련 모든 정보를 삭제한다.
        /// </summary>
        /// <param name="pcode">pcode</param>
        /// <returns>true/false</returns>
        private bool delAllInfo(string pcode)
        {
            try{

                if (pcode != null && pcode.Length == 10)
                {
                    if (DBUtil.deleteAllPTargetInfo(pcode))
                    {
                        return true;
                    }
                }

            }catch(Exception ex){

                throw new Exception(ex.Message);

            }

            return false;
            
        }

        //DataGridView 열 추가
        private void makeColumn()
        {
            colCandidates = new DataColumn("연번");
            colCandidates.DataType = typeof(int);
            colCandidates.AllowDBNull = true;
            colCandidates.ReadOnly = false;
            tblCandidates.Columns.Add(colCandidates);

            colCandidates = new DataColumn("개인번호");
            colCandidates.DataType = typeof(string);
            colCandidates.AllowDBNull = true;
            colCandidates.ReadOnly = false;
            tblCandidates.Columns.Add(colCandidates);

            colCandidates = new DataColumn("성명");
            colCandidates.DataType = typeof(string);
            colCandidates.AllowDBNull = true;
            colCandidates.ReadOnly = false;
            tblCandidates.Columns.Add(colCandidates);

            colCandidates = new DataColumn("성별");
            colCandidates.DataType = typeof(string);
            colCandidates.AllowDBNull = true;
            colCandidates.ReadOnly = false;
            tblCandidates.Columns.Add(colCandidates);

            dgvCandidates.DataSource = tblCandidates;

            dgvCandidates.Columns[0].Width = 40;
            dgvCandidates.Columns[1].Width = dgvCandidates.Width - 180;
            dgvCandidates.Columns[2].Width = 60;
            dgvCandidates.Columns[3].Width = 60;

            
        }

        //해당 직위의 대상자 불러오기
        private ArrayList getCadidates(int jobLevel)
        {
            if (jobLevel == -1) return null;

            ArrayList candidates = new ArrayList();

            //jobLevel에 따라 개인번호, 성멸, 성별을 불러온다.
            candidates = DBUtil.getCandidates(jobLevel);

            
            //결과가 없으면 null 리턴
            if (candidates == null || candidates.Count == 0)
            {
                return null;
            }
            else
            {
                return candidates;  
            }           
            
        }

        //DataGridView에 행 삽입
        private void makeRow(ArrayList candidates)
        {
            if (candidates == null || candidates.Count == 0) return;

            int i = 1;
            foreach (Hashtable hash in candidates)
            {
                DataRow row = tblCandidates.NewRow();
                row[0] = i.ToString();
                row[1] = hash["PCODE"];
                row[2] = hash["NAME"];
                row[3] = hash["SEX"];
                i++;                

                tblCandidates.Rows.Add(row);
            }

            dgvCandidates.DataSource = tblCandidates;

            //모든 Row를 읽기 전용으로 변경
            int cnt = dgvCandidates.Rows.Count;
            for (int j = 0; j < cnt; j++)
            {
                dgvCandidates.Rows[j].ReadOnly = true;
                dgvCandidates.Rows[j].DefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
            }
        }

        /// <summary>
        /// 추가한 행을 저장한다.
        /// </summary>
        /// <returns>true/false</returns>
        private bool saveRow()
        {
            try
            {
                Hashtable hash = new Hashtable();
                int lastRowIndex = dgvCandidates.Rows.Count - 1;

                if (lastRowIndex == -1) return false;

                hash["PCODE"] = dgvCandidates.Rows[lastRowIndex].Cells[1].Value;
                hash["NAME"] = dgvCandidates.Rows[lastRowIndex].Cells[2].Value;
                hash["SEX"] = dgvCandidates.Rows[lastRowIndex].Cells[3].Value;

                if (((string)hash["PCODE"]).Length != 10) throw new Exception("개인번호의 10개의 문자로 구성되어야 합니다.    ");
                if (((string)hash["NAME"]).Length < 2 || ((string)hash["NAME"]).Length > 4) throw new Exception("성명이 적절한 지 않습니다.    ");
                if (((string)hash["SEX"]).Length == 0) throw new Exception("성별을 선택하지 않았습니다.    ");

                if (DBUtil.saveCandidateInfo(hash))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvCandidates_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1 || e.ColumnIndex == -1) return;

                //성명
                parentForm.txtTarget.Text = (string)dgvCandidates.Rows[e.RowIndex].Cells[2].Value;

                //개인번호
                parentForm.txtPCode.Text = (string)dgvCandidates.Rows[e.RowIndex].Cells[1].Value;

                //조회 링크
                parentForm.lnkFindUser.Focus();
                parentForm.lnkFindUser.Select();

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lnkAddRow_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                addRow();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lnkDelRow_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                delRow();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lnkSaveRow_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                if (saveRow())
                {
                    dgvCandidates.Rows[dgvCandidates.Rows.Count - 1].ReadOnly = true;
                    dgvCandidates.Rows[dgvCandidates.Rows.Count - 1].Cells[3] = new DataGridViewTextBoxCell();

                    MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvCandidates_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.selectedRowIndex = e.RowIndex;
        }
    }
}
